using System;
using System.IO;
using System.Diagnostics;

namespace WillStott.MxAppToolbox
{

	/// <summary>
	/// Summary description for UniLog.
	/// </summary>
	public class UniLog 
	{
		private EventLog m_EventLog;
		private string   m_Name;

		public UniLog()
		{	//don't initialise m_EventLog here so that derived classes (MockUniLog) 
		}	//are not forced to use EventLog

		public virtual string Name
		{
			get { return m_Name; }
			set 
			{ 
				if ( m_Name == null )
				{
					m_Name = value;
					m_EventLog = new EventLog("Application", ".", m_Name);
				}
			}
		}

		public virtual bool WriteMsg (EventLogEntryType msgtype, string fmt, params object[] args)
		{
			bool rc = false;

			if ( (m_Name != null) && (m_Name.Length > 0))
			{
				string msg = fmt;
				try
				{
					msg = String.Format(fmt, args);
				}
				catch(Exception)
				{
				}
				m_EventLog.WriteEntry(msg, msgtype );
			}
			return rc;
		}

		public bool WriteLogToFile( string Filename )
		{
			bool rc = false;
			if ( (m_EventLog != null ) && (m_Name != null) && (m_Name.Length > 0))
			{
				StreamWriter file = null;
				try
				{
					file = new StreamWriter(Filename, false);
					foreach (EventLogEntry entry in m_EventLog.Entries )
					{
						if ( entry.Source == m_Name )
							file.WriteLine( entry.TimeGenerated + @": ["  + entry.EntryType + @"] " + entry.Message);
						rc = true;
					}
				}
				finally
				{
					if (file != null)
						file.Close();
				}
			}
			return rc;
		}
	}
}
